package com.aliwo.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author:xuyayuan
 * @date:2021/7/18 11:31
 * @description:针对订单接口进行网关层的限流
 */
@Component
public class OrderReateLimiterFilter extends ZuulFilter {

    // 创建令牌桶，每秒创建000个令牌
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(1000);

    /**
     * 功能描述:拦截器类型
     *
     * @param
     * @return java.lang.String
     * @author xuyayuan
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 功能描述:过滤器执行顺序，值越小，越优先执行.限流设置为最先执行
     *
     * @param
     * @return int
     * @author xuyayuan
     */
    @Override
    public int filterOrder() {
        return -4;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 针对订单接口进行过滤，执行run()方法,其他接口不执行过滤run()方法，针对订单接口进行网关的限流
        if ("/apigetway/order/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        if (!RATE_LIMITER.tryAcquire()) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
        }
        return null;
    }
}
